package cn.com.cifi.mars.service.impl;

import cn.com.cifi.mars.bean.bo.projecyByStages.FullPathOrgData;
import cn.com.cifi.mars.bean.bo.test.*;
import cn.com.cifi.mars.bean.dto.MymContractDto;
import cn.com.cifi.mars.bean.dto.VsMarsFeeDto;
import cn.com.cifi.mars.bean.dto.VsMarsGetinDto;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.CodeEnum;
import cn.com.cifi.mars.constant.IsDeleteEnum;
import cn.com.cifi.mars.entity.*;
import cn.com.cifi.mars.mapper.mars.SignPlanVersionDetailMapper;
import cn.com.cifi.mars.service.*;
import cn.com.cifi.mars.util.DateUtils;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import cn.com.cifi.mars.util.VersionNameUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: JingYuanXiang
 * @date: 2020/12/14 17:36
 */
@Slf4j
@Service
public class TestDataReportServiceImpl implements TestDataReportService {

    @Autowired
    private DmOdsMyVsMarsSContractService dmOdsMyVsMarsSContractService;
    @Autowired
    private VsMarsFeeService vsMarsFeeService;
    @Autowired
    private VsMarsGetinService vsMarsGetinService;
    @Autowired
    private VsMarsGetinzclService vsMarsGetinzclService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private SignPlanVersionService signPlanVersionService;
    @Autowired
    private ProjectByStagesService projectByStagesService;
    @Autowired
    private SignPlanVersionDetailMapper signPlanVersionDetailMapper;


    @Override
    public TestSalesData getTestSalesData(String projectId) {
        if(StringUtils.isBlank(projectId)){
            throw new MsgException(CodeEnum.REQUEST_PARAM_NOT_FULL_ERROR);
        }
        MdmProject mdmProject = projectService.selectByProjectId(projectId, IsDeleteEnum.NO.getKey());

        //TODO 接明源签约ESB数据修改
        List<MymContractDto> mymContractDtos = dmOdsMyVsMarsSContractService.selectByKingdeexmprojguid(mdmProject.getKingdeeProjectId());
        List<VsMarsFee> vsMarsFeeDtos = vsMarsFeeService.selectAllByProjectId(projectId);
//        List<VsMarsGetin> vsMarsGetinDtoList = vsMarsGetinService.selectAllByProjectId(projectId);
        List<VsMarsGetinzcl> vsMarsGetinzclList = vsMarsGetinzclService.selectByKingdeeProjectId(mdmProject.getKingdeeProjectId());

        Map<String, MymContractDto> contractMap = mymContractDtos.stream().collect(Collectors.toMap(MymContractDto::getTradeGUID, s -> s));



        List<TestSignRecordsBO> testSignRecordsList = mymContractDtos.stream()
                .map(s->new TestSignRecordsBO(s.getProjName(),s.getContractGUID(),s.getRoomInfo(),s.getYwgsDate(),s.getCjRmbTotal(),s.getCloseDate(),s.getBcTotal(),s.getAuditDate()))
                .collect(Collectors.toList());
        List<TestSignReceivableBO> testSignReceivableList = vsMarsFeeDtos.stream()
                .map(s->new TestSignReceivableBO(s.getStageName(),s.getContractGUID(),s.getRoomName(),s.getReceiptDate(),s.getReceiptAmount()))
                .collect(Collectors.toList());
        List<TestSignReceiptsBO> testSignReceiptsList = vsMarsGetinzclList.stream()
                .map(s->new TestSignReceiptsBO(s.getKingDeeProjFName(),contractMap.get(s.getSaleGUID()).getContractGUID(),contractMap.get(s.getSaleGUID()).getRoomInfo(),s.getGetDate(),s.getRmbAmount(),s.getZlAmount(),s.getClAmount()))
                .collect(Collectors.toList());

        TestSalesData testSalesData = new TestSalesData();
        testSalesData.setTestSignRecordsList(testSignRecordsList);
        testSalesData.setTestSignReceivableList(testSignReceivableList);
        testSalesData.setTestSignReceiptsList(testSignReceiptsList);
        testSalesData.filterCheckOutData();
        return testSalesData;
    }


    @Override
    public List<TestSignVersionData> getTestSignVersionData(String signVersionId) {
        SignPlanVersion signPlanVersion = signPlanVersionService.selectById(signVersionId);
        FullPathOrgData fullPathOrgData = projectByStagesService.getParentFullPathOrgData(signPlanVersion.getProjectfId());

        //获取签约计划详情列表
        List<SignPlanVersionDetail> signPlanVersionDetailList = signPlanVersionDetailMapper.selectByVersionId(signVersionId, IsDeleteEnum.NO.getKey());

        LocalDateTime earlyDateTime = signPlanVersionDetailList.stream()
                .min(Comparator.comparing(SignPlanVersionDetail::getSignPlanTime))
                .orElse(new SignPlanVersionDetail()).getSignPlanTime();

        LocalDateTime lastDateTime = signPlanVersionDetailList.stream()
                .max(Comparator.comparing(SignPlanVersionDetail::getSignPlanTime))
                .orElse(new SignPlanVersionDetail()).getSignPlanTime();

        //以组团id和组合业态分组，并已回款时间做升序排序,(key:组团ID，(key:组合业态编码，value:回款计划详情))
        Map<String, LinkedHashMap<String, List<SignPlanVersionDetail>>> signPlanDetailByGroupIdMap = signPlanVersionDetailList
                .stream().sorted(Comparator.comparing(SignPlanVersionDetail::getSignPlanTime))
                .collect(Collectors.groupingBy(SignPlanVersionDetail::getGroupId,
                        Collectors.groupingBy(s -> s.getProductCode() + s.getFreeType() + s.getBusinessType() + s.getProType(), LinkedHashMap::new, Collectors.toList())));

        List<TestSignVersionData> dataList = new ArrayList<>();
        for (Map.Entry<String, LinkedHashMap<String, List<SignPlanVersionDetail>>> entry : signPlanDetailByGroupIdMap.entrySet()){
            for (Map.Entry<String, List<SignPlanVersionDetail>> entry1 : entry.getValue().entrySet()){
                List<SignPlanVersionDetail> details = entry1.getValue();
                Map<String, SignPlanVersionDetail> signPlanDetailMapByYearMonth = entry1.getValue().stream().collect(Collectors.toMap(s -> LocalDateTimeUtils.formatTime(s.getSignPlanTime(), DateUtils.DATE_JFP_STR), s -> s));
                List<BigDecimal> moneyList = new ArrayList<>();
                for (LocalDateTime dateTime = earlyDateTime; dateTime.compareTo(lastDateTime) <= 0  ; dateTime = dateTime.plusMonths(1)) {
                    String yearMonth = LocalDateTimeUtils.formatTime(dateTime, DateUtils.DATE_JFP_STR);
                    SignPlanVersionDetail detail = signPlanDetailMapByYearMonth.get(yearMonth);
                    if(null == detail){
                        moneyList.add(BigDecimal.ZERO);
                    }else {
                        if(LocalDateTimeUtils.compareDate(detail.getSignPlanTime(),signPlanVersion.getCreateTime(),0)){
                            moneyList.add(detail.getEarlySignSumPriceActual().add(detail.getSupplySignSumPriceActual()));
                        }else {
                            moneyList.add(detail.getEarlySignSumPrice().add(detail.getSupplySignSumPrice()));
                        }
                    }
                }

                SignPlanVersionDetail signPlanDetail = null;
                if(CollectionUtils.isNotEmpty(details)){
                    signPlanDetail = details.get(0);
                }
                TestSignVersionData data = new TestSignVersionData();
                data.setProjectName(fullPathOrgData.getProjectName());
                data.setStageName(fullPathOrgData.getStageName());
                data.setVersionName(VersionNameUtils.getVersionName(signPlanVersion));
                data.setGroupName(signPlanDetail.getGroupName());
                data.setCombinationProductName(signPlanDetail.getProductName()+signPlanDetail.getFreeTypeName()+signPlanDetail.getBusinessTypeName()+signPlanDetail.getProTypeName());
                data.setAffiliationTime(signPlanVersion.getCreateTime());
                data.setMoneyList(moneyList);
                dataList.add(data);
            }
        }
        return dataList;
    }

    @Override
    public List<String> getTestSignTimeList(String signVersionId) {
        SignPlanVersion signPlanVersion = signPlanVersionService.selectById(signVersionId);

        //获取签约计划详情列表
        List<SignPlanVersionDetail> signPlanVersionDetailList = signPlanVersionDetailMapper.selectByVersionId(signVersionId, IsDeleteEnum.NO.getKey());

        LocalDateTime earlyDateTime = signPlanVersionDetailList.stream()
                .min(Comparator.comparing(SignPlanVersionDetail::getSignPlanTime))
                .orElse(new SignPlanVersionDetail()).getSignPlanTime();

        LocalDateTime lastDateTime = signPlanVersionDetailList.stream()
                .max(Comparator.comparing(SignPlanVersionDetail::getSignPlanTime))
                .orElse(new SignPlanVersionDetail()).getSignPlanTime();

        List<String> timeList = new ArrayList<>();
        for (LocalDateTime dateTime = earlyDateTime; dateTime.compareTo(lastDateTime) <= 0  ; dateTime = dateTime.plusMonths(1)) {
            String yearMonth = LocalDateTimeUtils.formatTime(dateTime, DateUtils.DATE_JFP_STR);
            timeList.add(yearMonth);
        }
        return timeList;
    }
}
